﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.ServiceModel.Configuration;
using System.Text;
using System.Windows.Forms;
using VNet.VisiSuite.Common.Resource;
using VNet.VisiSuite.Common.Security;
using VNet.VisiSuite.Service.Contact.Message.Base;
using VNet.VisiSuite.Service.Contact.Message.Security;
using VNet.VisiSuite.Service.Proxy;
using VNet.VisiSuite.VisiAdmin.Models;

namespace VNet.VisiSuite.VisiAdmin.Providers
{
    public class SecurityProvider
    {
        public static void Login(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            e.Result = null;

            if (worker != null && worker.CancellationPending == false)
            {
                var model = (LoginModel)e.Argument;
                if (!MappingClientEndpointAddress(model.ServiceUrl))
                    e.Result = new SignInResponse { Success = false, Error = new ServiceError { Description = ErrorMessages.ServiceUrlInvalid } };
                else if (worker != null && worker.CancellationPending == false)
                {
                    var client = new VNetVisiSuiteSecurityContractClient();
                    var request = new SignInRequest
                    {
                        UserName = model.UserName,
                        Password = model.Password,
                        InstallKey = model.InstallKey,
                    };
                    e.Result = client.SignIn(request);
                }
            }
        }

        public static void Logout(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            e.Result = null;

            if (worker != null && worker.CancellationPending == false)
            {
                var client = new VNetVisiSuiteSecurityContractClient();
                var request = new SignOutRequest
                {
                    Identity = UserTransportToken.UserIdentity,
                };
                e.Result = client.SignOut(request);
            }
        }

        private static bool MappingClientEndpointAddress(string url)
        {
            try
            {
                string httpStr = "http://";
                int index = url.IndexOf(httpStr);
                url = (index < 0) ? url : url.Remove(index, httpStr.Length);

                if (url[url.Length - 1] == '/')
                    url = url.Remove(url.Length - 1);

                // Get the application configuration file.
                var config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

                var endpoints = ((ClientSection)config.SectionGroups["system.serviceModel"].Sections["client"]).Endpoints;
                foreach (ChannelEndpointElement endpoint in endpoints)
                {
                    var uri = string.Format(@"{0}{1}/{2}", httpStr, url, endpoint.Address.AbsolutePath.Contains("VNetVisiSuiteService.svc/VNetVisiSuiteService") ? "VNetVisiSuiteService.svc/VNetVisiSuiteService" : "VNetVisiSuiteSecurityService.svc/VNetVisiSuiteSecurityService");
                    endpoint.Address = new Uri(uri);
                }
                // Save the configuration file.
                config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("system.serviceModel/client");

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
